<?php
/**
 * Created by PhpStorm.
 * User: chenzhitao
 * Date: 2018/4/7
 * Time: 下午3:18
 */

namespace App\Busi\Traits;


use App\Models\Voucher;

Trait VoucherTrait
{
    public function getVoucherByID($id){
        if(!$id){
            return "";
        }
        $where = [
            ["id","=",$id],
            ["flag","=",1]
        ];
        $field = ["id","name"];
        $data = Voucher::where($where)->select($field)->first()->toArray();
        if($data){
            return "<a class='success' href='voucher/".$data['id']."' target='_blank'>{$data['name']}</a><br>";
        }else{
            return "";
        }
    }
    public function getVoucherNameByID($id){
        if(!$id){
            return "";
        }
        $where = [
            ["id","=",$id],
            ["flag","=",1]
        ];
        $field = ["id","name"];
        $data = Voucher::where($where)->select($field)->first()->toArray();
        if($data){
            return $data['name'];
        }else{
            return "";
        }
    }
    public function getVoucherAmountByID($id){
        if(!$id){
            return "";
        }
        $where = [
            ["id","=",$id],
            ["flag","=",1]
        ];
        $field = ["id","amount"];
        $data = Voucher::where($where)->select($field)->first()->toArray();
        if($data){
            return $data['amount'];
        }else{
            return "";
        }
    }
    public function getVoucherList($page){
        $pageSize = 5;
        $where = [
            ["flag","=",1]
        ];
        $field = ["id","name","address","logo","star","view_num"];
        $data = Voucher::where($where)->select($field)->orderBy('show_order', 'asc')->paginate($pageSize);
        $total = $data->total();
        $pageNum =  ceil($total/$pageSize);

        $companyList = [];
        foreach ($data as &$item){
            $item["logo"] = config('admin.upload.host').$item['logo'];
            $subcateroys = $item->subcategorys;
            $category = " ";
            if($subcateroys != null){
                foreach ($subcateroys as &$cate){
                    $category .= $cate["category_name"]."-";
                }
                $category = substr($category,1,strlen($category)-1);
            }

            $item["categorys"] = $category;
            unset($item['subcategorys']);
            $companyList[] = $item;

        }
        $ret = [
            "totalPage"=>$pageNum,
            "currentPage"=>$data->currentPage(),
            "list"=>$companyList
        ];
    }
}